import 'package:flutter/material.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/map/constant/map_http_url.dart';
import 'package:p_location/map/res/search_person_detail.dart';
import 'package:p_location/map/res/user_path_detail.dart';
import 'package:p_location/map/res/user_path_info.dart';
import 'package:p_location/map/res/user_path_point.dart';
import 'package:p_location/map/res/user_path_res.dart';
import 'package:p_location/map/res/user_trace_area_info.dart';
import 'package:p_location/map/res/user_trace_floor_time.dart';
import 'package:p_location/map/ui/page_search_person.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_constants.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:p_location/trace/ui/page_trace_record.dart';
import 'package:p_location/user/obj/obj_map_path.dart';
import 'package:p_location/utils/navigator_util.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:p_location/utils/toast_util.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:math';
import 'package:dio/dio.dart';
import 'dart:convert' as convert;
import 'package:intl/intl.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_spin_fade_loader_indicator.dart';

class PagePersonTrace extends StatefulWidget {
  //具有固定目标的 查询
  final bool isSingleTrace;
  final SearchPersonDetail chosenSn;

  @override
  _PagePersonTraceState createState() => _PagePersonTraceState();

  PagePersonTrace({this.isSingleTrace = false, this.chosenSn});
}

class _PagePersonTraceState extends State<PagePersonTrace> {
  bool isSearchBoxHidden = false;
  bool isBottomSheetShow = false;
  bool isBuildIdObtained = false;

  String buildId = "";

  final DateFormat formatterForSubmit = new DateFormat('yyyy-MM-dd HH:mm:ss');
  final DateFormat formatter = new DateFormat('MM月dd日 HH:mm');
  final String hintText = "请输入姓名/定位卡号/车牌号";
  final Radius cornerRadius = Radius.circular(10);

  SearchPersonDetail chosenSn;

  DateTime startDateTime, endDateTime;

  var startDate = "";
  var endDate = "";

  bool isLoading = true;
  WebViewController controller;

  List<UserPathPoint> pathPoints = [];

  List<UserTraceAreaInfo> areas = [];

  bool isRequesting = false;
  //保存楼层的开始到结束的时间
  List<FloorAndTime> listT0AndT1 = [];

  String eMsg = "";

  @override
  void initState() {
    super.initState();
    readBuildInfo();
//    _requestPersonPath();
  }

  @override
  void dispose() {
    super.dispose();
//    controller.clearCache();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.isSingleTrace
          ? AppBar(
              title: Text("轨迹"),
              centerTitle: true,
              elevation: 0,
              brightness: Brightness.dark,
              leading: IconButton(
                  tooltip: '返回',
                  icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                  onPressed: () {
                    Navigator.of(context).pop();
                  }),
            )
          : null,
      body: _getContentView(),
    );
  }

  chooseDate(isEnd) {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: _setMinTime(startDateTime, isEnd),
        maxTime: _setMaxTime(startDateTime, isEnd), onChanged: (date) {
      print('change $date in time zone ' +
          date.timeZoneOffset.inHours.toString());
    }, onConfirm: (date) {
      print('confirm $date');
      if (date != null) {
        setState(() {
          var datetime = formatter.format(date);
          if (!isEnd) {
            startDateTime = date;
            endDateTime = date.add(Duration(hours: 4));
            startDate = datetime;
            endDate = formatter.format(endDateTime);
          } else {
            endDateTime = date;
            endDate = datetime;
          }
        });
      }
    }, locale: LocaleType.zh);
  }

  _getContentView() {
    return isBuildIdObtained
        ? (StringUtil.isNotEmpty(eMsg)
            ? NoResultWidget('images/img_no_accident.png', eMsg)
            : Stack(
                children: <Widget>[
                  GestureDetector(
                    onTapDown:(event){},
                    child: new WebView(
                        initialUrl:ObjMapPath.getInitUrl(true),
                        // 加载的url
                        javascriptMode: JavascriptMode.unrestricted,
                        navigationDelegate: (NavigationRequest request) {
                          if (request.url.startsWith('js://webview')) {
                          } else if (request.url
                              .startsWith("js://onMapLoadCompleted")) {
                            print("地图加载完毕...");
                            initMapMode();
                            setState(() {
//                      isLoading = false;
                            });
                          } else if (request.url
                              .startsWith("js://onReadConfigurationFailed")) {
                            setState(() {
//                      isLoading = false;
//                      isConfigurationLacked = true;
                              eMsg = "jpg地图缺失，请联系实施工程师";
                            });
                          }
                          return NavigationDecision.prevent;
                        },
                        onWebViewCreated: (WebViewController web) {
                          controller = web;
                        },
                        onPageFinished: (String value) {
                          setState(() {
                            isLoading = false;
                          });
                          // webview 页面加载调用
                          print('_controller$controller');
                        },
                        onWebResourceError:(error){
                          eMsg = "网页加载失败...";
                        }
                    ),
                  ),
                  Offstage(offstage: isSearchBoxHidden, child: searchBox),
                  Offstage(offstage: !isLoading, child: _getLoadingView()),
                  Positioned(
                    right: 20,
                    bottom: 30,
                    child: Offstage(
                      offstage: isBottomSheetShow || chosenSn == null,
                      child: GestureDetector(
                        onTap: () {
                          if (chosenSn != null) {
                            showBottomSheet();
                          }
                        },
                        child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.all(5),
                            child: Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Icon(
                                    Icons.remove_red_eye,
                                    size: 18,
                                  ),
                                )
                              ],
                            )),
                      ),
                    ),
                  ),
                  Positioned(
                    right: 20,
                    bottom: 80,
                    child: Offstage(
                      offstage: !isSearchBoxHidden,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchBoxHidden = false;
                          });
                        },
                        child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.all(5),
                            child: Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Icon(
                                    Icons.search,
                                    size: 18,
                                  ),
                                )
                              ],
                            )),
                      ),
                    ),
                  )
                ],
              ))
        : _getLoadingView();
  }

  _requestPersonPath() async {
    setState(() {
      isRequesting = true;
    });
    pathPoints = [];
    listT0AndT1 = [];
    Map<String, dynamic> params = {};
    params["sn"] = chosenSn.sn;
    params["startTime"] = formatterForSubmit.format(startDateTime);
    params["endTime"] = formatterForSubmit.format(endDateTime);
//    DioHttpClient.addHeader("buildid", "202722");
    await DioHttpClient.requestPost(
        context,
        MapHttpUrl.PEOPLE_PATH_SEARCH_URL,
        params,
        NetListenerImpl((Response response) {
          isRequesting = false;
          if (response != null && response.data != null) {
            UserPathRes res = UserPathRes.fromJson(response.data);
            if (res != null && res.code == 0 && res.data != null) {
              UserPathInfo userPathInfo = res.data;
              setState(() {
                /*if(userPathInfo != null){
=======
                if (userPathInfo != null) {
>>>>>>> dev
                  areas = userPathInfo.areas;
                }*/
                if (userPathInfo != null &&
                    userPathInfo.userPathGroupDTOList != null &&
                    userPathInfo.userPathGroupDTOList.length > 0) {
                  List<UserPathGroupDTO> groups =
                      userPathInfo.userPathGroupDTOList;
                  for (var i = 0; i < groups.length; i++) {

                    listT0AndT1.add(FloorAndTime(floorId: groups[i].floorId,beginTime: groups[i].t0,endTime: groups[i].t1));

                    List<UserPathPoint> points = groups[i].points;
                    if (points != null && points.length > 0) {
                      pathPoints.addAll(points);
                    }
                  }
                  //              if(pathPoints!= null && pathPoints.length > 15){
//                pathPoints = pathPoints.sublist(0,15);
//              }
                  print(convert.jsonEncode(pathPoints));
                  controller
                      ?.evaluateJavascript(
                          'addLineMarkers(${convert.jsonEncode(pathPoints)})')
                      ?.then((result) {
                    print('controller是否为null${controller == null}');
                    // You can handle JS result here.
                  });
                  print('取到了${pathPoints?.length}');
                  showBottomSheet();
                } else {
                  ToastUtil.showToast("该时间段没有轨迹信息");
                }
              });
            }
          }
        }, (CommonRes errorRes) {
          setState(() {
            isRequesting = false;
            if (errorRes != null) {
              ToastUtil.showToast(errorRes.msg);
            }
          });
        }),
        contentType: NetConstants.POST_TYPE_FORM,
        loadingTip: "查询中,请稍候...");
  }

  bool hasValidSn() {
    return chosenSn != null;
  }

  getSearchTextColor() {
    if (hasValidSn()) {
      return Colors.black;
    }
    return Color.fromRGBO(0, 0, 0, 0.5);
  }

  _setDefaultSearchTime() {
    DateTime endTime = DateTime.now();
    DateTime beginTime = endTime.subtract(Duration(hours: 4));

    setState(() {
      startDateTime = beginTime;
      endDateTime = endTime;
      startDate = formatter.format(beginTime);
      endDate = formatter.format(endTime);
    });
  }

  // startTime 是选中的startTime
  _setMinTime(DateTime startTime, bool isEndTime) {
    if (isEndTime) {
      if (startTime == null) {
        print('_setMinTime1${DateTime.now()}');
        return DateTime.now();
      }
      print('_setMinTime2${startTime.add(Duration(seconds: 1))}');
      return startTime.add(Duration(seconds: 1));
    } else {
      return DateTime.now().subtract(Duration(days: 365));
    }
  }

  _setMaxTime(DateTime startTime, bool isEndTime) {
    if (isEndTime) {
      DateTime endMaxTime = startTime.add(Duration(hours: 24));
      if ((DateTime.now()).compareTo(endMaxTime) == 1) {
        print('_setMaxTime1${endMaxTime}');
        return endMaxTime;
      }
      print('_setMaxTime2${DateTime.now()}');
      return DateTime.now();
    } else {
//      return startTime.add(Duration(minutes: (59 - startTime.minute)));
      return DateTime.now();
    }
  }

  checkConditionValid() {
    if (chosenSn == null) {
      ToastUtil.showToast("请先选择人员或者车辆");
      return;
    }
    if (startDateTime == null || endDateTime == null) {
      ToastUtil.showToast("请选择正确的开始时间和结束时间");
      return;
    }
    _requestPersonPath();
  }

  readBuildInfo() async {
    dynamic value = await SharedPreferenceHelp.read(SPKey.KEY_BUILD_ID);
    setState(() {
      buildId = value;
      isBuildIdObtained = true;
      setState(() {
        chosenSn = widget.chosenSn;
      });
      _setDefaultSearchTime();
    });
//    if (widget.isSingleTrace && chosenSn != null) {
//      _requestPersonPath();
//    }
  }

  _getLoadingView() {
    return Center(
      child: Loading(
          indicator: BallSpinFadeLoaderIndicator(),
          size: 100.0,
          color: Colors.blue),
    );
  }

  showBottomSheet() {
    setState(() {
      isSearchBoxHidden = true;
      isBottomSheetShow = true;
    });
    Future<void> future = showModalBottomSheet<void>(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (c) {
          return Offstage(offstage: false, child: _draggable);
        });
    future.then((void value) => _closeModal(value));
  }

  _closeModal(void value) {
    print("bottomSheet被关闭了");
    setState(() {
      isBottomSheetShow = false;
    });
  }

  _clearMapMarkers() {
    controller?.evaluateJavascript('clearAllMapMarkers()')?.then((result) {});
  }

  get _draggable => Container(
        padding: EdgeInsets.only(left: 10, right: 10, top: 10),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        child: Wrap(
          children: [
            Column(
              children: [
                Container(
                    padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                    alignment: Alignment.topRight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Column(
                          children: [
                            Image.asset(
                              "images/icon_inner_person.png",
                              width: 45,
                              height: 45,
                            ),
                            Container(
                              child: Text(
                                chosenSn?.name ?? "-",
                                style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 15),
                              ),
                            )
                          ],
                        ),
                        GestureDetector(
                          onTap: () {
                            NavigatorUtil.push(context, PageTraceRecord(listT0AndT1));
                          },
                          child: Container(
                            color: Colors.white,
//                            alignment: Alignment.center,
                            height: 40,
                            child: Text(
                              "查看轨迹记录",
                              style: TextStyle(
                                  fontSize: 15,
                                  color: Color.fromARGB(255, 26, 103, 250)),
                            ),
                          ),
                        ),
                      ],
                    )),
                Container(
                  height: 40,
                  child: Row(
                    children: [
                      Container(
                        width: 80,
                        child: Text("岗位:"),
                      ),
                      Text(chosenSn?.jobName ?? "")
                    ],
                  ),
                ),
                Container(
                  height: 40,
                  child: Row(
                    children: [
                      Container(
                        width: 80,
                        child: Text("部门:"),
                      ),
                      Text(chosenSn?.departName ?? "")
                    ],
                  ),
                ),
                Container(
                  height: 40,
                  child: Row(
                    children: [
                      Container(
                        width: 80,
                        child: Text("定位卡号:"),
                      ),
                      Text(chosenSn?.sn ?? "")
                    ],
                  ),
                ),
                Container(
                  height: 40,
                  child: Row(
                    children: [
                      Container(
                        width: 80,
                        child: Text("开始时间:"),
                      ),
                      Text(formatterForSubmit.format(startDateTime))
                    ],
                  ),
                ),
                Container(
                  height: 40,
                  child: Row(
                    children: [
                      Container(
                        width: 80,
                        child: Text("结束时间:"),
                      ),
                      Text(formatterForSubmit.format(endDateTime))
                    ],
                  ),
                )
              ],
            )
          ],
        ),
      );

  get briefInfoWidget => Container(
        padding: EdgeInsets.only(left: 10, right: 10, top: 10),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        child: Wrap(
          children: [
            Column(
              children: [
                Container(
                    padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
                    alignment: Alignment.topRight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Column(
                          children: [
                            Image.asset(
                              "images/icon_inner_person.png",
                              width: 45,
                              height: 45,
                            ),
                            Container(
                              child: Text(
                                "李尔澹",
                                style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 15),
                              ),
                            )
                          ],
                        ),
                        GestureDetector(
                          onTap: () {},
                          child: Container(
                            color: Colors.white,
//                            alignment: Alignment.center,
                            height: 40,
                            child: Text(
                              "查看轨迹记录",
                              style: TextStyle(
                                  fontSize: 15,
                                  color: Color.fromARGB(255, 26, 103, 250)),
                            ),
                          ),
                        ),
                      ],
                    )),
              ],
            )
          ],
        ),
      );

  initMapMode() async {
    String mapMode = await SharedPreferenceHelp.read(SPKey.KEY_MAP_MODE);
    if (StringUtil.isNotEmpty(mapMode)) {
      controller
          ?.evaluateJavascript(
          'setChosenMapType($mapMode)')
          ?.then((result) {});
    }
  }

  get searchBox => Container(
        margin: EdgeInsets.only(top: 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Offstage(
              offstage: false,
              child: Container(
                child: Flex(direction: Axis.horizontal, children: [
                  Expanded(
                      child: GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        PageSearchPerson(false))).then((value) {
                              print("选取了人员" + value.name);
                              setState(() {
                                chosenSn = value;
                              });
                            });
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                  topLeft: cornerRadius,
                                  topRight: cornerRadius),
                            ),
                            margin: EdgeInsets.fromLTRB(10, 3, 10, 0),
                            padding: EdgeInsets.all(12),
                            child: Row(
                              children: [
                                Icon(Icons.search,
                                    color: Color.fromRGBO(0, 0, 0, 0.5)),
                                Expanded(
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        margin: EdgeInsets.only(left: 6),
                                        child: Text(
                                            chosenSn != null
                                                ? chosenSn.name
                                                : hintText,
                                            style: TextStyle(
                                                color: getSearchTextColor())),
                                      ),
                                      Offstage(
                                        offstage: !hasValidSn(),
                                        child: GestureDetector(
                                          onTap: () {
                                            setState(() {
                                              chosenSn = null;
                                              _clearMapMarkers();
                                            });
                                          },
                                          child: Icon(Icons.clear,
                                              color:
                                                  Color.fromRGBO(0, 0, 0, 0.5)),
                                        ),
                                      )
                                    ],
                                  ),
                                  flex: 1,
                                )
                              ],
                            ),
                          )))
                ]),
              ),
            ),
            Container(
              height: 0.5,
              child: Text(""),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(10, 0, 10, 3),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        chooseDate(false);
                      },
                      child: Container(
                        color: Colors.white,
                        margin: EdgeInsets.fromLTRB(12, 9, 0, 8),
                        alignment: Alignment.topLeft,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              child: Text(
                                "开始时间",
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Color.fromARGB(99, 0, 0, 0)),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 5),
                              child: Text(
                                StringUtil.isEmpty(startDate)
                                    ? "请输入开始时间"
                                    : startDate,
                                style: TextStyle(
                                    fontSize: 17,
                                    color: Color.fromARGB(255, 0, 0, 0)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        chooseDate(true);
                      },
                      child: Container(
                        alignment: Alignment.topLeft,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              child: Text(
                                "结束时间",
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Color.fromARGB(99, 0, 0, 0)),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 5),
                              child: Text(
                                StringUtil.isEmpty(endDate)
                                    ? "请输入结束时间"
                                    : endDate,
                                style: TextStyle(
                                    fontSize: 17,
                                    color: Color.fromARGB(255, 0, 0, 0)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      bottomLeft: cornerRadius, bottomRight: cornerRadius)),
            ),
            GestureDetector(
              onTap: () {
                checkConditionValid();
              },
              child: Container(
                height: 45,
                margin: EdgeInsets.fromLTRB(10, 6, 10, 2),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(6)),
                    gradient: LinearGradient(
                        //渐变位置
                        begin: Alignment.topRight, //右上
                        end: Alignment.bottomLeft, //左下
                        stops: [
                          0.0,
                          1.0
                        ], //[渐变起始点, 渐变结束点]
                        //渐变颜色[始点颜色, 结束颜色]
                        colors: [
                          Color.fromRGBO(56, 160, 253, 0.9),
                          Color.fromRGBO(26, 103, 250, 0.9)
                        ])),
                child: FractionallySizedBox(
                    alignment: Alignment.center,
                    widthFactor: 1,
                    child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        isRequesting ? "查询中..." : "查询",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )
          ],
        ),
      );
}
